/**
 * 基于原生websocket， 封装socket方法
 *
 */






const socket = {
    // websocket 实例
    websocket: null,
    // 连接地址
    connectURL: '',
    // 开启标识
    socketOpen: false,
    // 心跳timer
    heartbeatTimer: null,
    // 心跳发送频率
    heartbeatInterval: 30000,
    // 异常跳动次数
    heartbeatCurrent: 0,
    // 允许最多异常跳动次数
    heartbeatCount: 3,
    // 是否自动重连
    isReconnect: true,
    // 重连频率
    reconnectInterval: 5000,
    // 重连次数
    reconnectCount: 5,
    // 已发起重连次数
    reconnectCurrent: 0,
    // 重连timer
    reconnectTimer: null,

    init: (router) => {
        // 检查当前浏览器是否支持 WebSocket
        if (!('WebSocket' in window)) {
            console.error('浏览器不支持WebSocket')
            return null
        }
        // 已经创建过连接不再重复创建
        // if (socket.websocket) {
        //   return socket.websocket
        // }
        // 连接地址
        socket.connectURL = `ws://127.0.0.1:3000?token=web`

        // 实例化socket
        socket.websocket = socket.websocket || new WebSocket(socket.connectURL)

        // 解说消息
        socket.websocket.onmessage = (e) => {
            const { data } = e
        
            let  info = data.substring(1, data.length - 1)

            console.log(info);
            // 心跳检测
            if (info === 'pong') {
                socket.heartbeatCurrent = 0
                return
            }


            


           
  
            switch (info) {
                case 'Build':
                    router.push({
                        name: 'Park'
                    });
                    break;
                case 'Park':
                    router.push({
                        name: 'Build'
                    });
                default:
                    break;
            }


        }

        // 连接成功
        socket.websocket.onopen = (e) => {
            console.log('websocket连接成功')
            socket.socketOpen = true
            socket.isReconnect = true
            // 开启心跳
            socket.heartbeat()
        }

        // 连接发生错误
        socket.websocket.onerror = (e) => {
            console.log('websocket连接失败')
        }

        // 关闭连接
        socket.websocket.onclose = (e) => {
            console.log('websocket断开连接')
            clearInterval(socket.heartbeatInterval)
            socket.socketOpen = false
            socket.websocket = null

            // 需要重新连接
            socket.reconnect()
        }
    },
    send: data => {
        if (socket.websocket && socket.websocket.readyState === socket.websocket.OPEN) {
            // 开启状态直接发送
            socket.websocket.send(data)
        } else {
            // 重置心跳
            clearInterval(socket.heartbeatTimer)
        }
    },

    receive: (message) => {
        let params = JSON.parse(JSON.parse(message.data).data)
        return params
    },
    heartbeat: () => {
        // 重置心跳
        if (socket.heartbeatTimer) {
            clearInterval(socket.heartbeatTimer)
        }
        socket.heartbeatTimer = setInterval(() => {
            // 超过允许最多异常跳动次数视为断线, 重新连接
            if (socket.heartbeatCurrent > socket.heartbeatCount) {
                clearInterval(socket.heartbeatTimer)
                socket.heartbeatCurrent = 0
                socket.reconnect()
            } else {
                socket.send(JSON.stringify('ping'))
                socket.heartbeatCurrent++
            }
        }, socket.heartbeatInterval)
    },
    // 关闭连接
    close: () => {
        clearInterval(socket.heartbeatTimer)
        clearTimeout(socket.reconnectTimer)
        socket.isReconnect = false
        socket.websocket && socket.websocket.close()
    },

    // 重新连接
    reconnect: () => {
        if (socket.isReconnect) {
            socket.reconnectTimer = setTimeout(() => {
                // 超过重连次数
                if (socket.reconnectCurrent >= socket.reconnectCount) {
                    clearTimeout(socket.reconnectTimer)
                    socket.isReconnect = false
                    return
                }
                // 记录重连次数
                socket.reconnectCurrent++

                if (!socket.isReconnect) {
                    socket.close()
                } else {
                    console.log('websocket正在重新连接')
                    socket.init(null)
                }
            }, socket.reconnectInterval)
        }
    }
}

export default socket;